<?PHP
/**
* 全局函数库 2009,12,01
*/
class func{
	# 实例化自己
	public static function & singleton()
	{
		static $instances;
		if (!isset ($instances))
		{
			$instances = new func();
		}
		return $instances;
	}
	/* 对象转化成数组 */
	public static function jsonToArray($val){
		if(is_object($val)){
			$val = get_object_vars($val);
		} 
		foreach ($val as $key => $value) {
			if (is_array($value) || is_object($value)) {
				$val[$key] = self::jsonToArray($value);
			} else {
				//$val[$key] = addslashes($value);
			} 
		}
		return $val;
	} 
	/* curl连接 */
	public static function data_encode($data, $keyprefix = "", $keypostfix = "") {
		assert( is_array($data) );
		$vars=null;
		foreach($data as $key=>$value) {
		 if(is_array($value)) 
		 		$vars .= self::data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
		 else 
		 		$vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
		}
		return $vars;
	}
	public static function curl_post($url='',$postfields=array(),$method='post',$timeout=60){
		$ch = @curl_init();
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, intval($timeout) ); //超时时间
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //以字符串输出结果
		if($method == 'post'){
			curl_setopt($ch, CURLOPT_POST, 1);       //POST方式
			curl_setopt($ch, CURLOPT_POSTFIELDS, substr(self::data_encode($postfields), 0, -1));//POST数据
			curl_setopt($ch, CURLOPT_URL, $url);//提交地址
		}else{
			# get方式
			curl_setopt($ch, CURLOPT_URL, $url.'?'.substr(self::data_encode($postfields), 0, -1));//提交地址
		}
		return @curl_exec($ch);
	}
	
	/* 通用重名检测 */
	public static function checkrepeat($table__,$cols__=array(),$primary_val__='0',$primary__='id'){
		$ret = true;
		if(is_array($cols__)){
			$db = getDBO();
			foreach($cols__ as $col){
				$table = $table__;
				if(isset($col['table'])) $table = $col['table'];
				
				$primary = $primary__;
				if(isset($col['primary'])) $primary = $col['primary'];
				
				$primary_val = $primary_val__;
				if(isset($col['primary_val'])) $primary_val = $col['primary_val'];
				 
				if($db->loadresult('select count(*) from `'.$table.'` where '.$col['col'].'="'.$col['val'].'" and '.$primary.'<>"'.$primary_val.'" ') > 0){
					$ret = $col;
					break;
				}
			}
		}
		return $ret;
	}
	/* 金额格式化 */
	public static function fnDec($val=0,$deci=2){
		return number_format($val, $deci, '.', '');
	}
	/* 查询条件组装 */
	public static function speedsearch($key,$fields_search){
		$keywords = rawurldecode($key);
		$tj = array ();
		if($keywords){
			foreach ($fields_search as $value) {
				$tj[] = addslashes($value) . ' LIKE \'%' . addslashes($keywords) . '%\'';
			}
			$tj = ' (' . implode(' OR ', $tj).' ) ';
		}else{
			$tj='';
		}
		if($tj != '') $tj = ' and '.$tj;
		return $tj;
	}	
	
	# 根据类型记录seccode
	public static function setSecCode($seccodename = '',$seccode){
		if($seccodename == '') $seccodename = 'default';
	
		 $_SESSION['seccode'][$seccodename] = strtoupper($seccode);
		
		return true;
		//return $_SESSION['seccode'][$seccodename] = strtoupper($seccode);
		
	}
	# 根据类型得到seccode
	public static function getSecCode($seccodename){
		return strtoupper($_SESSION['seccode'][$seccodename]);
	}
	
	# 登录密码加密方式
	public static function madepwd($str=''){
		return $str;
		//return md5(getcfg('secret','').md5($str)); 
	}
	
	
	# 产生guid码
	public static function guid(){
		static $instance;
		if(!isset($instance)){
			load('core.utils.guid');
		}
		$instance = new Guid();
		return $instance->toString();
	}	
	
	# 设置cookie
	static function setCookie($arg1,$arg2,$expire = NULL,$path = '/'){
		if(!$expire) $expire = getCfg('cookie_expire',0);
		$domain = '';
		if(getCfg('cookie_domain',1) == 0) $domain = substr($_SERVER['HTTP_HOST'],strpos($_SERVER['HTTP_HOST'],'.'));
    setcookie ($arg1,$arg2,time()+$expire,$path,$domain);
	}
	# 得到cookie
	static function getCookie($arg1){
		return $_COOKIE[$arg1];
	} 
	
	static function &env($key, $default = null) {
		$val = null;
		if (isset ($_SERVER[$key])) {
			$val =  $_SERVER[$key];
		}
		elseif (isset ($_ENV[$key])) {
			$val =  $_ENV[$key];
		}
		elseif (getenv($key) !== false) {
			$val =  getenv($key);
		}
		if ($val !== null) {
			return $val;
		} else {
			return $default;
		}
	}
	# 得服务器IP
	static function get_server_ip() {
		$val = self::env('REMOTE_ADDR');
		if ($val === self::env('SERVER_ADDR') && $ip = self::env('HTTP_PC_REMOTE_ADDR')) {
			return $ip;
		}
		return $val;
	}
	# 得客户端IP
	static function get_client_ip(){
		 if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
				 $ip = getenv("HTTP_CLIENT_IP");
		 else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
				 $ip = getenv("HTTP_X_FORWARDED_FOR");
		 else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
				 $ip = getenv("REMOTE_ADDR");
		 else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
				 $ip = $_SERVER['REMOTE_ADDR'];
		 else
				 $ip = "unknown";
		 return($ip);
	}
	# 格式化日期
	static function fmtDate($_timestamp=0){
		if($_timestamp !== 0)
			return date('Y-m-d H:i:s',$_timestamp);
		else
		return date('Y-m-d H:i:s');		
	}
	# 日期差额
	static function dateDiff($interval, $date1, $date2) {
		 if(!is_string($date1))	$date1 = date('Y-m-d H:i:s',$date1);
		 if(!is_string($date2))	$date2 = date('Y-m-d H:i:s',$date2);
		 $seconds = strtotime($date2) - strtotime($date1);
		 $date1=date("Y-m-d",strtotime($date1));
		 $date2=date("Y-m-d",strtotime($date2));
		 $interval = strtolower(trim($interval));
		 switch($interval) {
				 case "y":
						 list($year1, $month1, $day1) = explode('-', $date1);
						 list($year2, $month2, $day2) = explode('-', $date2);
						 $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
						 $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
						 $diff = $year2 - $year1;
						 if($month1 > $month2) {
								 $diff -= 1;
						 } elseif($month1 == $month2) {
								 if($day1 > $day2) {
										 $diff -= 1;
								 } elseif($day1 == $day2) {
										 if($time1 > $time2) {
												 $diff -= 1;
										 }
								 }
						 }
						 break;
				 case "m":
						 /* parses the year, month and days. split() was replaced with explode(), PHP Manual says it's faster */
						 list($year1, $month1, $day1) = explode('-', $date1);
						 list($year2, $month2, $day2) = explode('-',$date2);
						 $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
						 $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
						 $diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1);
	
						 if($day1 > $day2) {
								 $diff -= 1;
						 } elseif($day1 == $day2) {
								 if($time1 > $time2) {
										 $diff -= 1;
								 }
						 }
						 break;
				 case "w":
						 // Only simple seconds calculation needed from here on
						 $diff = floor($seconds / 604800);
						 break;
				 case "d":
						 $diff = floor($seconds / 86400);
						 break;
				 case "h":
						 $diff = floor($seconds / 3600);
						 break;      
				 case "i":
						 $diff = floor($seconds / 60);
						 break;      
				 case "s":
						 $diff = $seconds;
						 break;      
		 }
		 return $diff;
	} 
	#得到随机密码
	static function getRandPwd($wei=8){
		$a=array('A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
		$b=array('1','2','3','4','5','6','7','8','9');
		$c='';
		$wei = intval($wei);
		for($i=0;$i<$wei;$i++){
			if(rand(0,1)==0 ){
				$c.=$a[rand(0,23)];
			}else{
				$c.=$b[rand(0,8)];
			}
		} 
		return $c;
	}		
	# 得到指定字符，剩余长度用...代表
	static function strWidth($s='',$b=0,$e=10,$k='...',$c='utf-8'){
		$s = strip_tags($s);
		return mb_strimwidth($s,intval($b),intval($e),$k,$c);
		
	}
} 
?>